/*
 * Copyright 2017-2020 吴学文 and java110 team.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.java110.mall.chain.cmd.chainInoutOrder;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.java110.core.annotation.Java110Cmd;
import com.java110.core.annotation.Java110Transactional;
import com.java110.core.context.ICmdDataFlowContext;
import com.java110.core.event.cmd.Cmd;
import com.java110.core.event.cmd.CmdEvent;
import com.java110.core.factory.GenerateCodeFactory;
import com.java110.dto.chain.ChainSupplierProductDto;
import com.java110.dto.chain.ChainInoutOrderDto;
import com.java110.dto.chain.ChainSupplierDto;
import com.java110.dto.inoutOrder.InoutOrderDto;
import com.java110.dto.user.UserDto;
import com.java110.intf.cart.IInoutOrderInnerServiceSMO;
import com.java110.intf.cart.IInoutOrderProductInnerServiceSMO;
import com.java110.intf.chain.IChainCoreInnerServiceSMO;
import com.java110.intf.chain.IChainInoutOrderProductV1InnerServiceSMO;
import com.java110.intf.chain.IChainInoutOrderV1InnerServiceSMO;
import com.java110.intf.chain.IChainSupplierV1InnerServiceSMO;
import com.java110.intf.goods.IProductInnerServiceSMO;
import com.java110.intf.user.IUserV1InnerServiceSMO;
import com.java110.po.chainInoutOrder.ChainInoutOrderPo;
import com.java110.po.chainInoutOrder.ChainInoutOrderProductPo;
import com.java110.po.inoutOrder.InoutOrderPo;
import com.java110.po.inoutOrder.InoutOrderProductPo;
import com.java110.utils.exception.CmdException;
import com.java110.utils.util.Assert;
import com.java110.utils.util.BeanConvertUtil;
import com.java110.utils.util.StringUtil;
import com.java110.vo.ResultVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 类表述 集采接口
 * 服务编码：chainInoutOrder.saveChainInoutOrder
 * 请求路劲：/app/chainInoutOrder.SaveChainInoutOrder
 * add by 吴学文 at 2022-06-21 17:25:44 mail: 928255095@qq.com
 * open source address: https://gitee.com/wuxw7/MicroCommunity
 * 官网：http://www.homecommunity.cn
 * 温馨提示：如果您对此文件进行修改 请不要删除原有作者及注释信息，请补充您的 修改的原因以及联系邮箱如下
 * // modify by 张三 at 2021-09-12 第10行在某种场景下存在某种bug 需要修复，注释10至20行 加入 20行至30行
 */
@Java110Cmd(serviceCode = "chainInoutOrder.saveChainInoutOrder")
public class SaveChainInoutOrderCmd extends Cmd {

    private static Logger logger = LoggerFactory.getLogger(SaveChainInoutOrderCmd.class);

    public static final String CODE_PREFIX_ID = "15";

    @Autowired
    private IChainInoutOrderV1InnerServiceSMO chainInoutOrderV1InnerServiceSMOImpl;

    @Autowired
    private IChainInoutOrderProductV1InnerServiceSMO chainInoutOrderProductV1InnerServiceSMOImpl;

    @Autowired
    private IUserV1InnerServiceSMO userInnerServiceSMOImpl;

    @Autowired
    private IInoutOrderInnerServiceSMO inoutOrderInnerServiceSMOImpl;

    @Autowired
    private IInoutOrderProductInnerServiceSMO inoutOrderProductInnerServiceSMOImpl;

    @Autowired
    private IChainSupplierV1InnerServiceSMO chainSupplierV1InnerServiceSMOImpl;

    @Autowired
    private IChainCoreInnerServiceSMO chainCoreInnerServiceSMOImpl;

    @Autowired
    private IProductInnerServiceSMO roductInnerServiceSMOImpl;


    @Override
    public void validate(CmdEvent event, ICmdDataFlowContext cmdDataFlowContext, JSONObject reqJson) {
        Assert.hasKeyAndValue(reqJson, "csId", "请求报文中未包含csId");
        Assert.hasKeyAndValue(reqJson, "shopId", "请求报文中未包含商铺");

        if (!reqJson.containsKey("chainProductValueDtos")) {
            throw new IllegalArgumentException("未包含商品");
        }

        JSONArray products = reqJson.getJSONArray("chainProductValueDtos");
        if (products == null || products.size() < 1) {
            throw new IllegalArgumentException("未包含商品");
        }

    }

    @Override
    @Java110Transactional
    public void doCmd(CmdEvent event, ICmdDataFlowContext cmdDataFlowContext, JSONObject reqJson) throws  CmdException {

        String userId = cmdDataFlowContext.getReqHeaders().get("user-id");
        String storeId = cmdDataFlowContext.getReqHeaders().get("store-id");

        UserDto userDto = new UserDto();
        userDto.setUserId(userId);
        userDto.setPage(1);
        userDto.setRow(1);
        List<UserDto> userDtos = userInnerServiceSMOImpl.queryUsers(userDto);
        Assert.listOnlyOne(userDtos, "用户未空");

        //商品信息
        ChainSupplierProductDto chainSupplierProductDto = BeanConvertUtil.covertBean(reqJson, ChainSupplierProductDto.class);
        //订单信息
        ChainInoutOrderPo chainInoutOrderPo = BeanConvertUtil.covertBean(reqJson, ChainInoutOrderPo.class);
        chainInoutOrderPo.setOrderId(GenerateCodeFactory.getGeneratorId(CODE_PREFIX_ID));
        chainInoutOrderPo.setInOrderId(GenerateCodeFactory.getGeneratorId(ChainInoutOrderDto.ORDER_TYPE_IN));
        chainInoutOrderPo.setPersonId(userDtos.get(0).getUserId());
        chainInoutOrderPo.setPersonName(userDtos.get(0).getName());
        chainInoutOrderPo.setState(ChainInoutOrderDto.STATE_W);
        chainInoutOrderPo.setOrderType(ChainInoutOrderDto.ORDER_TYPE_IN);
        int flag = chainInoutOrderV1InnerServiceSMOImpl.saveChainInoutOrder(chainInoutOrderPo);
        if (flag < 1) {
            throw new CmdException("保存数据失败");
        }
        // 保存集采商品
        JSONArray products = reqJson.getJSONArray("chainProductValueDtos");
        ChainInoutOrderProductPo chainInoutOrderProductPo = null;
        String shopId = reqJson.getString("shopId");
        String groupId = reqJson.getString("groupId");
        for (int productIndex = 0; productIndex < products.size(); productIndex++) {
            chainInoutOrderProductPo = BeanConvertUtil.covertBean(products.getJSONObject(productIndex), ChainInoutOrderProductPo.class);
            String ruleId = products.getJSONObject(productIndex).get("ruleId").toString();
            chainInoutOrderProductPo.setCsId(reqJson.getString("csId"));
            chainInoutOrderProductPo.setRuleId(ruleId);//价格策略
            chainInoutOrderProductPo.setShopId(shopId);
            chainInoutOrderProductPo.setStoreId(storeId);
            chainInoutOrderProductPo.setGroupId(groupId);
            chainInoutOrderProductPo.setOrderId(chainInoutOrderPo.getOrderId());
            chainInoutOrderProductPo.setItemId(GenerateCodeFactory.getGeneratorId(CODE_PREFIX_ID));
            chainInoutOrderProductPo.setProdName(chainSupplierProductDto.getProdName());
            if (StringUtil.isEmpty(chainInoutOrderProductPo.getCount()) || chainInoutOrderProductPo.getCount().equals("0")){
                continue;
            }
            chainInoutOrderProductPo.setAmount((new BigDecimal(chainInoutOrderProductPo.getCount().trim())).multiply(new BigDecimal(chainInoutOrderProductPo.getPrice().trim()))+"");
            flag = chainInoutOrderProductV1InnerServiceSMOImpl.saveChainInoutOrderProduct(chainInoutOrderProductPo);
            if (flag < 1) {
                throw new CmdException("保存数据失败");
            }
        }
        ChainSupplierDto chainSupplierDto = new ChainSupplierDto();
        chainSupplierDto.setCsId(reqJson.getString("csId"));
        List<ChainSupplierDto> chainSupplierDtos = chainSupplierV1InnerServiceSMOImpl.queryChainSuppliers(chainSupplierDto);
        Assert.listOnlyOne(chainSupplierDtos,"供应商不存在");
        chainSupplierDto = chainSupplierDtos.get(0);
        try {
            saveSingileProduct(products,reqJson,storeId);
        } catch (Exception e) {
            e.printStackTrace();
            cmdDataFlowContext.setResponseEntity(ResultVo.error(e.getMessage()));
            return;
        }
        // 进货单
        inoutOrder(chainSupplierProductDto,products, chainInoutOrderPo, reqJson,chainSupplierDtos.get(0));
        //判断是否直接入库
        if(chainSupplierDto.getSuType() != null  && chainSupplierDto.getSuType().equals("2") ){//成熟链
            //进货进商品库
            try {
                doInoutOrder(products,chainInoutOrderPo,reqJson);
            } catch (Exception e) {
                e.printStackTrace();
                cmdDataFlowContext.setResponseEntity(ResultVo.error(e.getMessage()));
                return;
            }
    }
        cmdDataFlowContext.setResponseEntity(ResultVo.success());
    }

    private void saveSingileProduct(JSONArray products, JSONObject reqJson,String storeId) throws Exception {
        String shopId = reqJson.getString("shopId");
        String groupId = reqJson.getString("groupId");
        if (StringUtil.isEmpty(shopId) || StringUtil.isEmpty(storeId) || StringUtil.isEmpty(groupId)){
            throw new CmdException("店铺信息错误，请检查店铺信息");
        }
        for (int productIndex = 0; productIndex < products.size(); productIndex++) {
            String ruleId = products.getJSONObject(productIndex).get("ruleId").toString();
            ChainSupplierProductDto chainSupplierProductDto = new ChainSupplierProductDto();
            chainSupplierProductDto.setProductId(reqJson.getString("productId"));
            chainSupplierProductDto.setCsId(reqJson.getString("csId"));
            chainSupplierProductDto.setStoreId(storeId);
            chainSupplierProductDto.setShopId(shopId);
            chainSupplierProductDto.setGroupId(groupId);
            chainSupplierProductDto.setRuleId(ruleId);
            chainCoreInnerServiceSMOImpl.insertSingleProduct(chainSupplierProductDto);
        }
    }

    /**
     * 出库处理
     * @param products
     * @param chainInoutOrderPo
     * @param reqJson
     */
    private void doInoutOrder(JSONArray products, ChainInoutOrderPo chainInoutOrderPo, JSONObject reqJson) throws Exception {
        chainInoutOrderPo.setOrderId(chainInoutOrderPo.getOrderId());
        chainInoutOrderPo.setInOrderId(chainInoutOrderPo.getInOrderId());
        chainInoutOrderPo.setState(ChainInoutOrderDto.STATE_C);
        int flag = chainInoutOrderV1InnerServiceSMOImpl.updateChainInoutOrder(chainInoutOrderPo);
    }



    /**
     * 入库处理
     *
     * @param products
     * @param chainInoutOrderPo
     */
    private void inoutOrder(ChainSupplierProductDto chainSupplierProductDto,JSONArray products, ChainInoutOrderPo chainInoutOrderPo, JSONObject reqJson,ChainSupplierDto chainSupplierDto) {
        InoutOrderPo inoutOrderPo = new InoutOrderPo();
        inoutOrderPo.setOrderId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_orderId));
        inoutOrderPo.setShopId(reqJson.getString("shopId"));
        if(chainSupplierDto.getSuType() !=null  && chainSupplierDto.getSuType().equals("2") ){//成熟链
            inoutOrderPo.setState(InoutOrderDto.STATE_C);
        }else {
            inoutOrderPo.setState(InoutOrderDto.STATE_WI);
        }
        inoutOrderPo.setOrderType(InoutOrderDto.ORDER_TYPE_IN);
        inoutOrderPo.setPersonId(chainInoutOrderPo.getPersonId());
        inoutOrderPo.setPersonName(chainInoutOrderPo.getPersonName());
        inoutOrderPo.setRemark("添加商品初始化入库");
        //开始保存 inoutOrderProduct
        InoutOrderProductPo inoutOrderProductPo = null;
        List<InoutOrderProductPo> inoutOrderProductPos = new ArrayList<>();

        ChainInoutOrderProductPo chainInoutOrderProductPo = null;
        for (int productIndex = 0; productIndex < products.size(); productIndex++) {
            chainInoutOrderProductPo = BeanConvertUtil.covertBean(products.getJSONObject(productIndex), ChainInoutOrderProductPo.class);
            inoutOrderProductPo = new InoutOrderProductPo();
            inoutOrderProductPo.setRsId(chainSupplierDto.getCsId());
            inoutOrderProductPo.setSupplierName(chainSupplierDto.getName());
            inoutOrderProductPo.setPrice(chainInoutOrderProductPo.getPrice());
            inoutOrderProductPo.setProdCount(chainInoutOrderProductPo.getCount());
            BigDecimal price = new BigDecimal(Double.parseDouble(chainInoutOrderProductPo.getPrice()));
            if (StringUtil.isEmpty(chainInoutOrderProductPo.getCount()) || chainInoutOrderProductPo.getCount().equals("0")){
                continue;
            }
            price = price.multiply(new BigDecimal(Double.parseDouble(chainInoutOrderProductPo.getCount()))).setScale(2, BigDecimal.ROUND_HALF_EVEN);
            inoutOrderProductPo.setAmount(price.doubleValue() + "");
            inoutOrderProductPo.setItemId(GenerateCodeFactory.getGeneratorId("11"));
            inoutOrderProductPo.setOrderId(inoutOrderPo.getOrderId());
            inoutOrderProductPo.setProductId(chainInoutOrderProductPo.getProductId());
            inoutOrderProductPo.setProdName(chainSupplierProductDto.getProdName());
            inoutOrderProductPo.setShopId(inoutOrderPo.getShopId());
            inoutOrderProductPo.setState(InoutOrderDto.STATE_W);
            if(chainSupplierDto.getSuType() != null  && chainSupplierDto.getSuType().equals("2") ){//成熟链
                inoutOrderPo.setState(InoutOrderDto.STATE_C);
            }else {
                inoutOrderPo.setState(InoutOrderDto.STATE_WI);
            }
            inoutOrderProductPo.setValueId(chainInoutOrderProductPo.getValueId());
            inoutOrderProductPo.setRemark("集采统一入库");
            inoutOrderProductPo.setSpecName("商品规格");
            inoutOrderProductPos.add(inoutOrderProductPo);
        }
        int flag = inoutOrderProductInnerServiceSMOImpl.saveInoutOrderProducts(inoutOrderProductPos);
        if (flag < 1){
            throw new IllegalArgumentException("提交失败");
        }
        flag = inoutOrderInnerServiceSMOImpl.saveInoutOrder(inoutOrderPo);
        if (flag < 1){
            throw new IllegalArgumentException("提交失败");
        }
    }
}
